package com.weimob.mcloud.wechatwork.customer.mq;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.weimob.artemis.client.consumer.model.ConsumerRecord;
import com.weimob.artemis.client.consumer.model.MessageResult;
import com.weimob.artemis.client.spring.annotation.ArtemisConsumerListener;
import com.weimob.artemis.client.spring.annotation.Subscribe;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.ac.req.BWidChangeSecondMsg;
import com.weimob.mcloud.wechatwork.core.base.SingleResponse;
import com.weimob.mcloud.wechatwork.core.entity.relation.tag.MarkTagTask;
import com.weimob.mcloud.wechatwork.core.enums.account.BWidChangeHandleStatusEnum;
import com.weimob.mcloud.wechatwork.core.enums.account.ContainBWidTableEnum;
import com.weimob.mcloud.wechatwork.core.service.account.BWidChangeRecordCoreService;
import com.weimob.mcloud.wechatwork.core.service.account.request.BWidChangeRecord;
import com.weimob.mcloud.wechatwork.core.service.account.request.SingleBWidChangeRecordRequest;
import com.weimob.mcloud.wechatwork.core.service.tag.TagTaskCoreService;
import com.weimob.mcloud.wechatwork.core.service.tag.request.SingleTagTaskRequest;
import com.weimob.mcloud.wechatwork.customer.domain.ArtemisConstant;
import com.weimob.soa.common.response.SoaResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 功能描述:
 *
 * @author lvjunlong
 * @date 2023/6/19 上午11:18
 */
@Slf4j
@Service
public class AccountChangeSecondMsgConsume {

    @Reference
    private TagTaskCoreService tagTaskCoreService;

    @Autowired
    private BWidChangeRecordCoreService bWidChangeRecordCoreService;

    @ArtemisConsumerListener(
            value = @Subscribe(topic = ArtemisConstant.Topic.WECHATWORK_BOS_WID_CHANGE, user = ArtemisConstant.USER), interval = 50)
    public void bWidChangeSecond(MessageResult result) {

        List<ConsumerRecord> records = result.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return;
        }

        for (ConsumerRecord consumerRecord : records) {

            log.info("bWid变更二次分发消息消费, message:{}", consumerRecord.getValue());

            BWidChangeSecondMsg bWidChangeSecondMsg = JSON.parseObject(consumerRecord.getValue(), BWidChangeSecondMsg.class);
            if (Objects.isNull(bWidChangeSecondMsg)) {
                continue;
            }
            if (StringUtils.isNotBlank(bWidChangeSecondMsg.getTabName())
                    && !ContainBWidTableEnum.MARK_TAG_TASK.getTable().equals(bWidChangeSecondMsg.getTabName())) {
                continue;
            }

            try {

                //查询记录表是否存在，如果不存在，则插入一条
                SingleBWidChangeRecordRequest<BWidChangeRecord> getRequest = new SingleBWidChangeRecordRequest<>();
                BWidChangeRecord getBWidChangeRecord = toBWidChangeRecord(bWidChangeSecondMsg);
                getRequest.setData(getBWidChangeRecord);

                SoaResponse<SingleResponse<BWidChangeRecord>, Void> soaResponse = bWidChangeRecordCoreService.getOneByMsgId(getRequest);
                if (0L != Long.parseLong(soaResponse.getReturnCode())) {
                    log.error("查询bwid变更记录失败, request:{}, response:{}", JSON.toJSONString(getRequest), JSON.toJSONString(soaResponse));
                    continue;
                }

                SingleResponse<BWidChangeRecord> bWidChangeRecordSingleResponse = soaResponse.getResponseVo();
                if (Objects.isNull(bWidChangeRecordSingleResponse) || Objects.isNull(bWidChangeRecordSingleResponse.getData())) {
                    SingleBWidChangeRecordRequest<BWidChangeRecord> saveRequest = new SingleBWidChangeRecordRequest<>();
                    BWidChangeRecord saveBWidChangeRecord = toBWidChangeRecord(bWidChangeSecondMsg);
                    saveBWidChangeRecord.setStatus(BWidChangeHandleStatusEnum.INIT.getStatus());
                    saveRequest.setData(saveBWidChangeRecord);
                    bWidChangeRecordCoreService.save(saveRequest);
                } else {
                    BWidChangeRecord bWidChangeRecord = bWidChangeRecordSingleResponse.getData();
                    if (bWidChangeRecord.getStatus().equals(BWidChangeHandleStatusEnum.SUCCESS.getStatus())) {
                        continue;
                    }
                }

                //处里业务表mark_tag_task, 将originWid更新为wid
                updateMarkTagTaskTable(bWidChangeSecondMsg);

                //更新记录表
                SingleBWidChangeRecordRequest<BWidChangeRecord> updateRequest = new SingleBWidChangeRecordRequest<>();
                BWidChangeRecord updateBWidChangeRecord = toBWidChangeRecord(bWidChangeSecondMsg);
                updateBWidChangeRecord.setStatus(BWidChangeHandleStatusEnum.SUCCESS.getStatus());
                updateRequest.setData(updateBWidChangeRecord);
                bWidChangeRecordCoreService.update(updateRequest);

            } catch (Exception e) {
                log.error("bWid变更二次分发消息消费失败, record:{}, error:{}", consumerRecord, e);

                //更新记录表
                SingleBWidChangeRecordRequest<BWidChangeRecord> updateRequest = new SingleBWidChangeRecordRequest<>();
                BWidChangeRecord updateBWidChangeRecord = toBWidChangeRecord(bWidChangeSecondMsg);
                updateBWidChangeRecord.setStatus(BWidChangeHandleStatusEnum.FAIL.getStatus());
                updateRequest.setData(updateBWidChangeRecord);
                bWidChangeRecordCoreService.update(updateRequest);
            }
        }
    }

    private void updateMarkTagTaskTable(BWidChangeSecondMsg bWidChangeSecondMsg) {

        //记录表插入一条
        //根据bWid滚动查询表mark_tag_task
        //根据主键id、originWid更新表mark_tag_task

        Long nextId = 0L;
        while (true) {
            SingleTagTaskRequest<MarkTagTask> request = new SingleTagTaskRequest<>();
            request.setNextId(nextId);
            request.setOriginWid(bWidChangeSecondMsg.getOriginalWid());
            request.setLimit(50);
            SoaResponse<SingleResponse<List<MarkTagTask>>, Void> soaResponse = tagTaskCoreService.scroll(request);
            if (0L != Long.parseLong(soaResponse.getReturnCode()) || Objects.isNull(soaResponse.getResponseVo())) {
                log.error("滚动查询批量打标签任务失败, msg:{}", JSON.toJSONString(soaResponse));
                break;
            }

            List<MarkTagTask> markTagTaskList = soaResponse.getResponseVo().getData();
            if (CollectionUtils.isEmpty(markTagTaskList)) {
                break;
            }

            nextId = markTagTaskList.get(markTagTaskList.size() - 1).getTaskId();
            if (Objects.isNull(nextId)) {
                log.error("job 滚动查询批量打标签任务, nextId为空");
                break;
            }

            List<Long> idList = covert2IdList(markTagTaskList);

            SingleTagTaskRequest<MarkTagTask> updateRequest = new SingleTagTaskRequest<>();
            updateRequest.setIdList(idList);
            updateRequest.setOriginWid(bWidChangeSecondMsg.getOriginalWid());
            updateRequest.setWid(bWidChangeSecondMsg.getWid());
            tagTaskCoreService.updateWid(updateRequest);
        }
    }

    private List<Long> covert2IdList(List<MarkTagTask> markTagTaskList) {
        if (CollectionUtils.isEmpty(markTagTaskList)) {
            return new ArrayList<>();
        }

        List<Long> idList = new ArrayList<>();
        for (MarkTagTask markTagTask : markTagTaskList) {
            idList.add(markTagTask.getTaskId());
        }

        return idList;
    }

    private BWidChangeRecord toBWidChangeRecord(BWidChangeSecondMsg bWidChangeSecondMsg) {
        BWidChangeRecord bWidChangeRecord = new BWidChangeRecord();
        bWidChangeRecord.setMsgId(bWidChangeSecondMsg.getMsgId());
        bWidChangeRecord.setBosId(bWidChangeSecondMsg.getBosId());
        bWidChangeRecord.setTabName(ContainBWidTableEnum.MARK_TAG_TASK.getTable());
        bWidChangeRecord.setOriginalWid(bWidChangeSecondMsg.getOriginalWid());
        bWidChangeRecord.setWid(bWidChangeSecondMsg.getWid());

        return bWidChangeRecord;
    }
}
